package com.clw.classfile;

import java.io.IOException;
import java.io.Reader;

/**
 * Created by chengliwei on 2018/12/18.
 */
public class BytesReader {

    private byte[] bytes;
    private int pos = 0;

    private BytesReader(byte[] bytes) {
        this.bytes = bytes;
    }

    public static BytesReader use(byte[] bytes) {
        return new BytesReader(bytes);
    }

    public byte readByte(){
        return bytes[pos++];
    }

    public int read() {
        return bytes[pos++] & 0xff;
    }

    public String readUTF8(int length) {
        return new String(readBytes(length));
    }

    public int readInt() {
        int b1 = read();
        int b2 = read();
        int b3 = read();
        int b4 = read();
        return (b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0);
    }

    public short readShort() {
        int b1 = read();
        int b2 = read();
        return (short) ((b1 << 8) + (b2 << 0));
    }

    public byte[] readBytes(int length) {
        byte[] resultBytes = new byte[length];
        for (int i = 0; i < length; i++) {
            resultBytes[i] = bytes[pos++];
        }
        return resultBytes;
    }

    public long readLong() {
        byte[] bytes = readBytes(8);
        return (((long)bytes[0] << 56) +
                ((long)(bytes[1] & 255) << 48) +
                ((long)(bytes[2] & 255) << 40) +
                ((long)(bytes[3] & 255) << 32) +
                ((long)(bytes[4] & 255) << 24) +
                ((bytes[5] & 255) << 16) +
                ((bytes[6] & 255) <<  8) +
                ((bytes[7] & 255) <<  0));
    }
}
